<?php

    namespace yaliSDK\utils;
    class Json {
        static public function toJson($d, $options = JSON_UNESCAPED_UNICODE) {

            $array = [];
            foreach ($d as $k => $item) {
                switch (gettype($item)) {
                    case 'object':
                        $array[$k] = $item->__toString();
                        break;
                    case 'array':
                        $array[$k] = json_encode($item);
                        break;
                    default:
                        $array[$k] = $item;
                        break;
                }
            }
            return json_encode($array, $options);
        }

        static public function classToArray($data) {
            switch (gettype($data)) {
                case 'object': {
                    $funcs = get_class_methods($data);
                    $array = [];
                    foreach ($funcs as $func) {
                        if (preg_match('/^get[A-Z]*/', $func)) {
                            $d = explode('get', $func, 2);
                            $array[lcfirst($d[1])] = Json::classToArray($data->$func());
                        } else if (preg_match('/^is[A-Z]*/', $func)) {
                            $array[lcfirst($func)] = Json::classToArray($data->$func());
                        }
                    }
                    return $array;
                    break;
                }
                case 'array': {
                    $array = [];
                    foreach ($data as $index => $item) {
                        $array[$index] = Json::classToArray($item);

                    }
                    return $array;
                    break;
                }
                default: {
                    return $data;
                }
            }
        }
    }